package io.jft.doll.ui.cart

import android.arch.lifecycle.ViewModelProviders
import android.databinding.ObservableField
import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.g.base.api.ErrorCode
import com.g.base.extend.observeEx
import com.g.base.extend.progressDialog
import com.g.base.extend.resultNotNull
import com.g.base.extend.toast
import com.g.base.help.postSimpleNotify
import com.g.base.room.entity.UserEntity
import com.g.base.room.repository.ListStatus
import com.g.base.room.repository.Status
import com.g.base.router.RouteExtras
import com.g.base.ui.BaseActivity
import com.g.base.ui.recyclerView.decoration.LinearItemDecoration
import com.g.base.ui.recyclerView.item.BaseItem
import com.g.base.ui.recyclerView.setupRecyclerView
import io.jft.doll.R
import io.jft.doll.databinding.ActivityCartBinding
import io.jft.doll.event.NotifyUrl
import io.jft.doll.model.bindModel.AddressBind
import io.jft.doll.model.viewModel.AddressViewModel
import io.jft.doll.model.viewModel.CartViewModel
import io.jft.doll.room.entity.common.AddressItemCEntity
import io.jft.doll.room.entity.remote.CartREntity
import io.jft.doll.router.RouterPage
import io.jft.doll.ui.cart.bind.CartItemBind

/**
 * Created by G on 2017/12/11 0011.
 */
@Route(path = RouterPage.CartActivity, extras = RouteExtras.NeedOauth)
class CartActivity : BaseActivity<ActivityCartBinding>() {
    override var hasToolbar: Boolean = true
    private val cartViewModel by lazy { ViewModelProviders.of(this).get(CartViewModel::class.java) }
    private val addressViewModel by lazy { ViewModelProviders.of(this).get(AddressViewModel::class.java) }
    private var status = ListStatus.Content
    private var data: CartREntity? = null
    private val adapter by lazy { setupRecyclerView(contentView.recyclerView) }
    val addressBind by lazy {
        AddressBind(AddressItemCEntity(), isCartModel = true)
                .apply {
                    setOnClickListener {
                        ARouter.getInstance().build(RouterPage.AddressActivity).withBoolean("isSelectModel", true).navigation(this@CartActivity)
                    }
                }
    }

    val isSelectAll = ObservableField<Boolean>(false)
    val allCount = ObservableField(0)
    val postage = ObservableField<String>("--")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_cart)
        contentView.data = this
        initView()
        obsData()
        onReload()
    }


    override fun onTokenChange(data: UserEntity?) {
        if (data == null) {
            showNeedOauth()
        } else {
            onReload()
        }
    }

    override fun onReload() {
        cartViewModel.operateCartList()
        status = ListStatus.Content
    }


    private fun initView() {
        toolbar.title = "寄存中的娃娃"
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_toolbar_24dp)
        toolbar.setNavigationOnClickListener { finishAfterTransition() }

        toolbar.inflateMenu(R.menu.charge)
        toolbar.setOnMenuItemClickListener {
            ARouter.getInstance().build(RouterPage.RechargeActivity).navigation(this)
            true
        }

        contentView.recyclerView.addItemDecoration(LinearItemDecoration(this))

        contentView.swipeLayout.setOnRefreshListener {
            if (status == ListStatus.Content) {
                onReload()
                status = ListStatus.Refreshing
            } else {
                contentView.swipeLayout.isRefreshing = false
                toast("正在刷新中 请稍后再试")
            }
        }
    }

    private fun obsData() {
        addressViewModel.getSelect()
                .resultNotNull()
                .observeEx(this) {
                    when (it.status) {
                        Status.Loading -> {
                            addressBind.isLoading.set(true)
                            return@observeEx
                        }
                        Status.Content -> {
                            addressBind.beanItem.set(it.data)
                            addressBind.isLoading.set(false)
                        }
                        Status.Error -> {
                            addressViewModel.operateAllAddress(false)
                        }
                    }
                    contentView.address.data = addressBind
                    contentView.address.executePendingBindings()
                }

        addressViewModel.obsAllAddress()
                .resultNotNull()
                .observeEx(this) {
                    if (it.status == Status.Error) {
                        addressBind.isLoading.set(false)
                        addressBind.beanItem.set(AddressItemCEntity(consignee = "点我选择一个收货地址", address = "没有选中的收货地址"))
                    }
                }

        cartViewModel.obsProductList()
                .resultNotNull()
                .observeEx(this) {
                    when (it.status) {
                        Status.Loading -> {
                            if (status == ListStatus.Content) showLoading()
                        }
                        Status.Content -> {
                            data = it.data!!
                            if (status == ListStatus.Refreshing)
                                contentView.swipeLayout.isRefreshing = false
                            if (data!!.wawaList.isEmpty()) {
                                showEmpty("还没有可以领取的娃娃哦~ 快去抓几个吧!")
                            } else {
                                showContentView()
                            }
                            applyData()
                        }
                        Status.Error -> {
                            if (status == ListStatus.Content)
                                if (it.error?.code == ErrorCode.EMPTY) {
                                    if (data != null) {
                                        data!!.wawaList.clear()
                                        applyData()
                                    }
                                    showEmpty("还没有可以领取的娃娃哦~ 快去抓几个吧!")
                                } else {
                                    showError()
                                }
                            else
                                contentView.swipeLayout.isRefreshing = false
                            status = ListStatus.Content
                        }
                    }
                }
    }

    private fun applyData() {
        data ?: return
        val data = data!!

        isSelectAll.set(data.isCheckedAll)
        postage.set(if (data.postage == 0) "包邮" else "${data.postage} (娃娃币)")
        var allCount = 0
        data.wawaList.forEach {
            if (it.isChecked) {
                allCount += it.amount
            }
        }
        this.allCount.set(allCount)
        adapter.diffItems.addAll(data.wawaList.map {
            CartItemBind(it)
                    .apply {
                        setOnClickListener { _ ->
                            onCheckOneClick(it.id, !it.isChecked)
                        }
                    }
        })

        adapter.calcDiffAndDispatchUpdate(
                { baseItem: BaseItem<*>, i: Int, baseItem1: BaseItem<*>, i1: Int ->
                    (baseItem as CartItemBind).item.id == (baseItem1 as CartItemBind).item.id
                },
                { baseItem: BaseItem<*>, i: Int, baseItem1: BaseItem<*>, i1: Int ->
                    (baseItem as CartItemBind).item == (baseItem1 as CartItemBind).item
                }
        )
    }

    private fun onCheckOneClick(id: String, checked: Boolean) {
        cartViewModel.selectProductToCart(id, checked)
                .progressDialog()
                .observeEx(this) {
                    if (it.status == Status.Error) {
                        toast(it.error?.message ?: "未知错误")
                    }
                }
    }

    fun onCheckAllClick(view: View) {
        data ?: return
        val data = data!!

        cartViewModel.selectAllToCart(!data.isCheckedAll)
                .progressDialog()
                .observeEx(this) {
                    if (it.status == Status.Error) {
                        toast(it.error?.message ?: "未知错误")
                    }
                }
    }

    fun onCheckoutClick(view: View) {
        val data = data ?: return
        val id = addressBind.beanItem.get()?.id
        when {
            data.wawaList.isEmpty() -> toast("你似乎还没有寄存中的娃娃!~ 快去抓几个娃娃吧!")
            id == null || id.isEmpty() -> toast("请先选择一个收货地址")
            else -> cartViewModel.applyShipping(id)
                    .progressDialog { it.dismiss(true);postSimpleNotify(NotifyUrl.DollDetailActivity) }
                    .observeEx(this) {
                        if (it.status == Status.Error) {
                            toast(it.error?.message ?: "未知错误")
                        }
                    }
        }
    }
}